package com.roin.learn.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息生产者<br>
 * 
 * @author 罗毅
 * @version 1.0,2017年5月27日 下午3:10:33
 * @since learn-jms 0.0.1
 */
public class JmsProducer {
	/**
	 * 默认用户名
	 */
	private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
	/**
	 * 默认密码
	 */
	private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
	/**
	 * 默认连接地址
	 */
	private static final String BROKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;

	public static void main(String[] args) {
		// 连接工厂
		ConnectionFactory factory;
		// 连接
		Connection connection;
		// 会话，接收或者发送消息的线程
		Session session;
		// 消息目的地
		Destination destination;
		// 消息生产者
		MessageProducer messageProducer;
		// 实例化连接工厂
		factory = new ActiveMQConnectionFactory(USERNAME, PASSWORD, BROKER_URL);
		try {
			// 通过工厂获取连接
			connection = factory.createConnection();
			// 启动连接
			connection.start();
			//创建Session
			session = connection.createSession(true,Session.AUTO_ACKNOWLEDGE);
			//创建一个为HelloWorld的消息队列
			destination = session.createQueue("HelloWorld");
			//创建生产者
			messageProducer = session.createProducer(destination);
			//发送消息
			sendMessage(session,messageProducer);
			session.commit();
		} catch (JMSException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 发送消息<br>
	 * @param session
	 * @param messageProducer 消息生产者
	 * @throws JMSException 
	 * @since learn-jms 0.0.1
	 */
	private static void sendMessage(Session session, MessageProducer messageProducer) throws JMSException {
		for (int i = 0; i < 10; i++) {
			//创建一条文本消息
			TextMessage msg = session.createTextMessage("ActiveMQ发送消息"+i);
			System.out.println("ActiveMQ发送消息"+i);
			messageProducer.send(msg);
		}
	}

}
